
class MyWebsocket {
    constructor(url) {
        const ws = this.ws = new WebSocket(url);
        this.handler = {};
        ws.onopen = () => {
            console.log('ws is openss')
        };
        ws.onmessage = (message) => {
            let data = JSON.parse(message.data);
            const type = data.type;
            delete data.type;
            const handleFunc = this.handler[type];
            if (handleFunc) {
                handleFunc(data);
            }
        };

        ws.onerror = () => {
            ws.close();
        };

        ws.onclose = () => {
            console.log('ws close...')
        };
    }

    on(type, handleFunc) {
        if (this.handler[type]) {
            return alert('重复监听事件, type: ', type);
        }

        this.handler[type] = handleFunc;
    }
    $emit(type, data) {
        data.type = type;

        this.ws.send(JSON.stringify(data));
    }
};
